package com.gosophia.util;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter;

/**
 * 防止直接从浏览器地址栏输入地址 及 非法盗链
 */
public class RefererChainFilter extends StrutsPrepareAndExecuteFilter {

//	private FilterConfig filterConfig;
	
    /**
     * Default constructor. 
     */
    public RefererChainFilter() {
        super();
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		super.destroy();
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
		
//        if (req.getHeader("X-Requested-With") != null && req.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest")) {
//        	request.setCharacterEncoding("utf-8");
//        } else {
//        	request.setCharacterEncoding("gbk");
//        }
        
		String referer = req.getHeader("referer");
		
//		主机名
		String sitePart = "http://" + request.getServerName();
		
		if (null == referer || referer.startsWith(sitePart)) {   
//           正常页面请求
             super.doFilter(request, response, chain);
        }else{
//           盗链
             req.getRequestDispatcher("/jsp/error.jsp").forward(req, resp);
        }
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		super.init(fConfig);
	}
}
